<template>
  <div>
    <x-header id="header" :left-options="{backText: ''}">我的推广</x-header>
    <div class="main-header">
      <div class="spread-main">
        <div class="spread-con">
          <div class="spread-qrCode" id="img">
            <img style="height:100%;width:100%;display: block" :src="imageUrl" />
            <canvas id="canvas" class="spread-qrCode-canvas" ></canvas>
          </div>
          <div class="spread-tips">请扫一扫上面的推广我的推广码</div>
        </div>
        <!--<div class="save">-->
          <!--<x-button class="save-button" plain  @click.native="saveQrcode('loan_qrcode', imageUrl )" >保存到本地</x-button>-->
        <!--</div>-->
      </div>
    </div>
  </div>
</template>

<script>
import QRcode from 'qrcode'
export default {
  name: 'spread',
  data () {
    return {
      image: new Image(),
      imageUrl: '',
      url:'http://h5-dk.aiyueshou.com' || 'http://h5-dk.001as.net'
    }
  },
  methods: {
    saveQrcode(fileName, content) {
      let aLink = document.createElement('a');
      let blob = this.base64ToBlob(content); //new Blob([content]);
      let file = this.blobToFile(blob, fileName);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(file);
      // aLink.dispatchEvent(evt);
      // aLink.click()
      aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: false, view: window}));//兼容火狐
    },
    base64ToBlob(code) {
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {type: contentType});
    },
    blobToFile: function(theBlob, fileName){
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },
  },
  mounted () {
    let canvas = document.querySelector('#canvas');
    let _this = this
    QRcode.toCanvas(canvas, `${this.url}?shareId=${this.globalData.cid}`,
      { type: "png", width: 270, margin:1 },
      function (error) {
      if (error) console.error(error)
      // console.log_this.imageUrl(canvas.toDataURL("image/png"),base64.encode(canvas.toDataURL("image/png")))
      // _this.image.src = canvas.toDataURL("image/png");
      // let div  = document.getElementById('img');
      // div.appendChild(_this.image);
      _this.imageUrl = canvas.toDataURL("image/png")

    })
    this.$vux.toast.text('长按二维码保存到相册')
  }
}
</script>

<style scoped>

.save {
  width: 90%;
  margin: 0 auto;
}
.save-button {
  color: #fff;
  border-color: #fff;
}
</style>
